package com.gel.codegeneration.manager;

import com.gel.codegeneration.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @BelongsProject: code-generation-platform
 * @BelongsPackage: com.gel.codegeneration.manager
 * @Author: gel
 * @CreateTime: 2025-08-25  17:53
 * @Description: TODO
 * @Version: 1.0
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     * @param key 唯一键
     * @param file 源文件
     * @return
     */

    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return putObjectResult;
    }
    /**
     * 上传对象到COS
     * @param key 唯一键
     * @param file 源文件
     * @return
     */
    public String uploadFile(String key, File file){
        PutObjectResult putObjectResult = putObject(key, file);
        if (putObjectResult != null) {
            //构造访问url
            String url = String.format("%s%s", cosClientConfig.getHost(), key);
            log.info("上传成功，访问地址为：{}", url);
            return url;
        }else {
            log.error("上传失败");
            return null;
        }
    }
}
